Insert Sort

#C#

Posted by Phyxsius on 2023-09-28


internal class Program
{
    private static void Main(string[] args)
    {
        int[] ary = new int[5];    //宣告陣列大小為10

        Random rnd = new Random();  //產生亂數初始值

        for (int i=0; i<ary.Length; i++)
        {
            ary[i] = rnd.Next(1, 10);   //亂數產生,亂數產生的範圍是1~9
        }

        Console.WriteLine("原始陣列內容:");
        showArray(ary);

        InsertSort(ary);

        Console.WriteLine("由小到大排序後陣列內容:");
        showArray(ary);
    }

    static void InsertSort(int[] ary)
    {
        System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();
        stopWatch.Start();  //計算程式時間開始

        int counter = 0;

        //從第2個數值開始判斷(i=1)
        for (int i=1; i<ary.Length; i++)
        {
            for(int j=i; j>0; j--)
            {
                if (ary[j] < ary[j-1])
                {
                    swap(ary, j, j - 1);
                }

                if (j == 1) break;

                counter++;
            }
            Console.Write($"第{i + 1}輪結果:");
            showArray(ary);
        }
        Console.WriteLine("執行次數:" + counter);

        stopWatch.Stop();   //計算程式時間結束
        Console.WriteLine("程式執行時間(秒):" + (stopWatch.Elapsed.TotalMilliseconds/1000));
    }

    //兩個值互相交換
    static void swap(int[] ary, int value1, int value2)
    {
        int tmp = ary[value2];
        ary[value2] = ary[value1];
        ary[value1] = tmp;
    }

    //顯示陣列內容
    static void showArray(int[] ary)
    {
        for (int i=0; i<ary.Length; i++)
        {
            Console.Write(ary[i] + ",");
        }
        Console.WriteLine();
    }
}

#C#







Related Posts

在 Windows 上測試 Safari

在 Windows 上測試 Safari

來學 React 吧之七_React 實作留言板

來學 React 吧之七_React 實作留言板

V-for 的使用

V-for 的使用


Comments